// leetcode 349 两数组集合  
var intersection = function(num1, num2) {
  const map = new Map()
  num1.forEach(n => {
    map.set(n, true)
  })
  const res = []
  num2.forEach(n=> {
    if(map.get(n)) {
      res.push(n)
      map.delete(n)
    }
  })
  return res
}
// leetcode 20 有效的括号
var isValid = function(s) {
  if(s.length % 2 === 1) return false
  const stack = []
  const map = new Map()
  map.set('(', ')')
  map.set('{', '}')
  map.set('[', ']')
  for(let i = 0; i<s.length; i+=1) {
    const c = s[i]
    if(map.has(c)) {
      stack.push(c)
    }else{
      const t = stack[stack.length - 1]
      if(map.get(t) === c) {
        stack.pop()
      }else{
        return false
      }
    }
  }
  return stack.length === 0
}
// leetcode 1 两数之和
var twoSum = function (nums, target) {
  let map = new Map()
  for(let i = 0; i<nums.length; i+=1) {
    let n = nums[i]
    let d = target - n
    if(map.has(d)) {
      return [map.get(d), i]
    }else{
      map.set(n, i)
    }
  }
}

// leetcode 3 无重复字符的最长子串
var lengthOfLongestSubstring = function(s) {
  let l = 0 
  let res = 0
  const map = new Map()
  for(let r = 0; r<s.length;r++){
      let n = s[r]
      if(map.has(n)&&map.get(n)>=l){
          l = map.get(n)+1
      }
      res = Math.max(res, r-l+1)       
      map.set(n, r)
  }
  return res
};

// leetcode 76 最小覆盖子串
var check = function(map) {
  let arr = [...map.values()]
  let min = Math.min(...arr)
  let max = Math.max(...arr)
  return {
    dis: max-min,
    arr: [min, max]
  }
}
var minWindow = function(s, t) {
  let needMap = new Map()
  let resMap = new Map()
  let min = Infinity
  let arr = [0,0]
  for(let i =0; i<t.length; i++){
    let c = t[i]
      needMap.set(c, needMap.has(c) ? needMap.get(c)+1 : 1)
  }
  let needcount = t.length
  for(let i=0;i<s.length;i++){
      let n = s[i]
      if(needMap.has(n) && needcount != 0){

          resMap.set(n, i)
          if(needMap.get(n)!==0) {
              needcount-- 
              needMap.set(n, needMap.get(n)-1)
          }
          if(needcount==0) {
              // 计算
              let obj = check(resMap)
              if(obj.dis<min) {
                min = obj.dis
                arr = obj.arr
              }
          }
      }else if(needMap.has(n) && needcount == 0){
          resMap.set(n, i)
          let obj = check(resMap)
          if(obj.dis<min) {
            min = obj.dis
            arr = obj.arr
          }
      }
  }

  return needcount == 0 ? s.slice(arr[0], arr[1]+1) : ''
};
minWindow("aa","aa")